package top.wangjiu.reactive.rpc.config;

import io.netty.channel.ChannelOption;
import io.netty.util.AttributeKey;
import lombok.Data;
import top.wangjiu.reactive.rpc.client.RpcClientContainer;
import top.wangjiu.reactive.rpc.generater.HashMethodNameIdGenerater;
import top.wangjiu.reactive.rpc.generater.RequestIdGenerater;
import top.wangjiu.reactive.rpc.registration.ServerAddrList;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.*;

@Data
public class ClientConfiguration {

    private final Map<ChannelOption<Object>, Object> options = new LinkedHashMap();

    private final Map<AttributeKey<Object>, Object> attrs = new ConcurrentHashMap();

    private final RequestIdGenerater requestIdGenerater = new HashMethodNameIdGenerater();

    private ServerAddrList serverAddrList;

    private boolean autoReconnect = false;

    private int maxAutoReconnectTime = 3;

    /**
     * netty只负责接收请求的响应，这个是处理响应的线程数，为0则为默认线程数，也就是cpu核数的两倍,
     * 当然也可以自己指定线程池
     */
    private int responseProcessThread = 0;

    private final RpcClientContainer container = new RpcClientContainer(this);

    private Executor reponseExecutor;

    public Executor getResponseExecutor() {
        if(reponseExecutor==null){
            synchronized (this){
                if(reponseExecutor ==null){
                    reponseExecutor =  buildDefaultExecutor();
                }
            }
        }
        return reponseExecutor;
    }

    private Executor buildDefaultExecutor(){
        int threadCount = responseProcessThread <=0 ? Runtime.getRuntime().availableProcessors() : responseProcessThread;
        return new ThreadPoolExecutor(threadCount, threadCount*2, 5, TimeUnit.MINUTES,
                new ArrayBlockingQueue(10, true),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
